// pages/appoint/my/my.js
import {$http, formatTime} from './../../../utils/util'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hasAppoint: false,
    showModal: false,
    id: null,
    appointment: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id: options.id
    })
    // 1.设置屏幕高度
    this.setHeight();
  },
  onShow: function() {
    // 2.加载今天的预约单
    this.loadCurrentAppointment();
  },
  /**
   * 加载用户今天已经预约的信息
   */
  loadCurrentAppointment() {
    let appointments = wx.getStorageSync('appointments');
    if (this.data.id) {
      let filtered = appointments.filter(item => item.id == this.data.id);
      if (filtered) {
        this.setData({
          hasAppoint: true,
          appointment: filtered[0]
        })
      } else {
        this.setData({
          hasAppoint: false,
          appointment: null
        })
      }
    } else {
      this.setData({
        hasAppoint: false,
        appointment: null
      })
    }
    
  },
  /**
   * 设置屏幕高度
   */
  setHeight() {
    let {windowHeight} = wx.getSystemInfoSync();
    this.setData({
      // 使用自定义导航栏时页面的高度
      // windowHeight: (windowHeight - wx.getStorageSync('statusBarHeight')
      //     - wx.getStorageSync('navigationBarHeight')) + 'px',
      // 不使用自定义导航栏时页面的高度
      windowHeight: windowHeight + 'px'
    })
  },
  /**
   * 弹窗
   */
  showDialogBtn: function () {
    this.setData({
      showModal: true
    })
  },
  /**
   * 弹出框蒙层截断touchmove事件
   */
  preventTouchMove: function () {
  },
  /**
   * 隐藏模态对话框
   */
  hideModal: function () {
    this.setData({
      showModal: false
    });
  },
  /**
   * 对话框取消按钮点击事件
   */
  onCancel: function () {
    this.hideModal();
  },
  /**
   * 取消预约
   */
  onConfirm: function () {
    this.hideModal();
    $http.get({
      url: '/disAppoint',
      data: {appointmentId: this.data.appointment.id},
      success: res => {
        if (res.data.code === 200) {
          wx.showToast({
            title: res.data.msg,
            icon: 'success',
            duration: 2000
          });
          let appointments = wx.getStorageSync('appointments');
          if (appointments) {
            let filtered = appointments.filter(item => item.id != this.data.appointment.id);
            wx.setStorageSync('appointments', filtered);
          };
          this.setData({
            appointment: null,
            hasAppoint: false
          });
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/home/home',
            })
          }, 1000)
          
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络出错',
          icon: 'error',
          duration: 2000
        })
      }
    })
  }
})